package goods

import (
	"context"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/goods"
	goodsReq "github.com/flipped-aurora/gin-vue-admin/server/model/goods/request"
)

type LsGoodsService struct{}

// CreateLsGoods 创建lsGoods表记录
// Author [yourname](https://github.com/yourname)
func (lsGoodsService *LsGoodsService) CreateLsGoods(ctx context.Context, lsGoods *goods.LsGoods) (err error) {
	//err = global.GVA_DB.Create(lsGoods).Error
	if len(lsGoods.ManyPrice) == 0 {
		err = global.GVA_DB.Create(lsGoods).Error
	} else {
		var Goods []goods.LsGoods
		for _, price := range lsGoods.ManyPrice {
			var good = lsGoods
			good.Price = price.Price
			good.MarketPrice = price.MarketPrice
			good.CostPrice = price.CostPrice
			good.Stock = price.Stock
			good.Weight = price.Weight
			good.Volume = price.Volume
			good.BarCode = price.BarCode
			Goods = append(Goods, *good)
		}
		err = global.GVA_DB.Create(&Goods).Error
	}
	return err
}

// DeleteLsGoods 删除lsGoods表记录
// Author [yourname](https://github.com/yourname)
func (lsGoodsService *LsGoodsService) DeleteLsGoods(ctx context.Context, ID string) (err error) {
	err = global.GVA_DB.Delete(&goods.LsGoods{}, "id = ?", ID).Error
	return err
}

// DeleteLsGoodsByIds 批量删除lsGoods表记录
// Author [yourname](https://github.com/yourname)
func (lsGoodsService *LsGoodsService) DeleteLsGoodsByIds(ctx context.Context, IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]goods.LsGoods{}, "id in ?", IDs).Error
	return err
}

// UpdateLsGoods 更新lsGoods表记录
// Author [yourname](https://github.com/yourname)
func (lsGoodsService *LsGoodsService) UpdateLsGoods(ctx context.Context, lsGoods goods.LsGoods) (err error) {
	err = global.GVA_DB.Model(&goods.LsGoods{}).Where("id = ?", lsGoods.ID).Updates(&lsGoods).Error
	return err
}

// GetLsGoods 根据ID获取lsGoods表记录
// Author [yourname](https://github.com/yourname)
func (lsGoodsService *LsGoodsService) GetLsGoods(ctx context.Context, ID string) (lsGoods goods.LsGoods, err error) {
	//err = global.GVA_DB.Where("id = ?", ID).First(&lsGoods).Error
	db := global.GVA_DB.Model(&goods.LsGoods{})
	db = db.Joins("join ls_brand on ls_goods.brand_id = ls_brand.id")
	db = db.Joins("join ls_suppliers on ls_goods.suppiler_id=ls_suppliers.id")
	db = db.Joins("join ls_classifications on ls_goods.classify_id = ls_classifications.id")
	db = db.Where("ls_goods.id = ?", ID)
	db = db.Select("ls_goods.*,ls_brand.brand_name as brand,ls_classifications.classify_name as classify,ls_suppliers.supplier_name as suppiler")
	err = db.First(&lsGoods).Error
	return
}

// GetLsGoodsInfoList 分页获取lsGoods表记录
// Author [yourname](https://github.com/yourname)
func (lsGoodsService *LsGoodsService) GetLsGoodsInfoList(ctx context.Context, info goodsReq.LsGoodsSearch) (list []goods.LsGoods, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&goods.LsGoods{})
	var lsGoodss []goods.LsGoods
	// 如果有条件搜索 下方会自动创建搜索语句
	db = db.Joins("join ls_brand on ls_goods.brand_id = ls_brand.id")
	db = db.Joins("join ls_suppliers on ls_goods.suppiler_id=ls_suppliers.id")
	db = db.Joins("join ls_classifications on ls_goods.classify_id = ls_classifications.id")
	if len(info.CreatedAtRange) == 2 {
		db = db.Where("ls_goods.created_at BETWEEN ? AND ?", info.CreatedAtRange[0], info.CreatedAtRange[1])
	}

	if info.GoodType != nil && *info.GoodType != "" {
		db = db.Where("ls_goods.good_type = ?", *info.GoodType)
	}
	if info.GoodCode != nil && *info.GoodCode != "" {
		db = db.Where("ls_goods.good_code = ?", *info.GoodCode)
	}
	if info.GoodName != nil && *info.GoodName != "" {
		db = db.Where("ls_goods.good_name LIKE ?", "%"+*info.GoodName+"%")
	}
	if info.BrandId != nil {
		db = db.Where("ls_goods.brand_id = ?", *info.BrandId)
	}
	if info.SuppilerId != nil {
		db = db.Where("ls_goods.suppiler_id = ?", *info.SuppilerId)
	}
	if info.StartPrice != nil && info.EndPrice != nil {
		db = db.Where("ls_goods.price BETWEEN ? AND ? ", *info.StartPrice, *info.EndPrice)
	}
	if info.StartMarketPrice != nil && info.EndMarketPrice != nil {
		db = db.Where("ls_goods.market_price BETWEEN ? AND ? ", *info.StartMarketPrice, *info.EndMarketPrice)
	}
	if info.StartCostPrice != nil && info.EndCostPrice != nil {
		db = db.Where("ls_goods.cost_price BETWEEN ? AND ? ", *info.StartCostPrice, *info.EndCostPrice)
	}
	if info.StartStock != nil && info.EndStock != nil {
		db = db.Where("ls_goods.stock BETWEEN ? AND ? ", *info.StartStock, *info.EndStock)
	}
	if info.StartWeight != nil && info.EndWeight != nil {
		db = db.Where("ls_goods.weight BETWEEN ? AND ? ", *info.StartWeight, *info.EndWeight)
	}
	if info.StartVolume != nil && info.EndVolume != nil {
		db = db.Where("ls_goods.volume BETWEEN ? AND ? ", *info.StartVolume, *info.EndVolume)
	}
	if info.BarCode != nil && *info.BarCode != "" {
		db = db.Where("ls_goods.bar_code LIKE ?", "%"+*info.BarCode+"%")
	}
	if info.LogisticsWay != nil && *info.LogisticsWay != "" {
		db = db.Where("ls_goods.logistics_way = ?", *info.LogisticsWay)
	}
	if info.ShipFeeSet != nil && *info.ShipFeeSet != "" {
		db = db.Where("ls_goods.ship_fee_set = ?", *info.ShipFeeSet)
	}
	if info.StartShipFee != nil && info.EndShipFee != nil {
		db = db.Where("ls_goods.ship_fee BETWEEN ? AND ? ", *info.StartShipFee, *info.EndShipFee)
	}
	if info.GoodDetail != nil && *info.GoodDetail != "" {
		db = db.Where("ls_goods.good_detail LIKE ?", "%"+*info.GoodDetail+"%")
	}
	if info.GoodStatus != nil && *info.GoodStatus != "" {
		db = db.Where("ls_goods.good_status = ?", *info.GoodStatus)
	}
	if info.GoodSearchType != nil && *info.GoodSearchType != "" {
		db = db.Where("ls_goods.good_search_type = ?", *info.GoodSearchType)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	db = db.Select("ls_goods.*,ls_brand.brand_name as brand,ls_classifications.classify_name as classify,ls_suppliers.supplier_name as suppiler")
	err = db.Find(&lsGoodss).Error
	return lsGoodss, total, err
}
func (lsGoodsService *LsGoodsService) GetLsGoodsPublic(ctx context.Context) ([]goods.LsBrand, []goods.LsSuppliers, []goods.CliLsClassifications) {
	// 此方法为获取数据源定义的数据
	// 请自行实现
	Brands := GetBrand()
	Suppliers := GetSupplier()
	CliLsClassifications := GerClassTree()
	return Brands, Suppliers, CliLsClassifications
}

func GerClassTree() []goods.CliLsClassifications {
	db := global.GVA_DB
	var LsClassifications []goods.LsClassifications
	db.Model(&goods.LsClassifications{}).Find(&LsClassifications)
	var ClassMap = make(map[int16][]goods.LsClassifications)
	for _, classification := range LsClassifications {
		ClassMap[classification.ParentId] = append(ClassMap[classification.ParentId], classification)
	}
	tree := BuildTree(ClassMap[0], ClassMap)
	return tree
}

func BuildTree(classifications []goods.LsClassifications, classMap map[int16][]goods.LsClassifications) []goods.CliLsClassifications {
	var Res []goods.CliLsClassifications
	for _, classification := range classifications {
		res := goods.CliLsClassifications{
			Id:           classification.Id,
			CreatedAt:    classification.CreatedAt,
			UpdatedAt:    classification.UpdatedAt,
			DeletedAt:    classification.DeletedAt,
			ClassifyName: classification.ClassifyName,
			ParentId:     classification.ParentId,
			ClassifyIcon: classification.ClassifyIcon,
			Sort:         classification.Sort,
			Enable:       classification.Enable,
			CreatedBy:    classification.CreatedBy,
			UpdatedBy:    classification.UpdatedBy,
			DeletedBy:    classification.DeletedBy,
			CliClass:     BuildTree(classMap[int16(classification.Id)], classMap),
		}
		Res = append(Res, res)
	}
	return Res
}

func GetSupplier() []goods.LsSuppliers {
	db := global.GVA_DB
	var Suppliers []goods.LsSuppliers
	db.Model(&goods.LsSuppliers{}).Find(&Suppliers)
	return Suppliers
}

func GetBrand() []goods.LsBrand {
	db := global.GVA_DB
	var Brands []goods.LsBrand
	db.Model(&goods.LsBrand{}).Find(&Brands)
	return Brands
}
